package org.jeecg.modules.weixin.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.util.HttpRequest;
import org.jeecg.modules.weixin.entity.SysWxCampus;
import org.jeecg.modules.weixin.service.ISysWxCampusService;
import org.jeecg.modules.weixin.utill.WXConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* @Description: 微信公众号
* @Author: jeecg-boot
* @Date:   2020-08-20
* @Version: V1.0
*/
@Api(tags="系统微信公众号配置")
@RestController
@RequestMapping("/weixin/wx")
@Slf4j
public class WeiXinController extends JeecgController<SysWxCampus, ISysWxCampusService> {


   @Autowired
   private ISysWxCampusService sysWxCampusService;

   private final Logger logger = LoggerFactory.getLogger(getClass());

   /**
    * 路由控制
    *
    * @param request
    * @param code
    * @return
    */
   @GetMapping(value = "/auth")
   public Result<?> auth(HttpServletRequest request,
                        @RequestParam("code") String code) {
      JSONObject jsonObject = WXConstants.getUserAccessTokenInfo(code);//通过这个code获取access_token
      logger.info("try getUserAccessTokenInfo :"+jsonObject);
      String openId = (String) jsonObject.get("openid");
      if (openId!=null) {
         logger.info("try getting user info. openid:"+openId);
         JSONObject wxUserObject = WXConstants.getWXUserInfo((String)jsonObject.get("access_token"), openId);//使用access_token获取用户信息
         logger.info("received wxUserObject  [result={}]", wxUserObject);
         return Result.ok(wxUserObject);
      }
      return Result.ok("openid为空");
   }


   /**
    * 获取请求用户信息的access_token
    *
    * @param code
    * @return
    */
   @GetMapping(value = "/getUserAccessTokenInfo")
   public JSONObject getUserAccessTokenInfo(String code) {
      return WXConstants.getUserAccessTokenInfo(code);
   }

   /**
    * 与公众号服务器配置进行比对
    * @param req
    * @param res
    */
   @GetMapping(value = "/getWxToken")
   public void getWxToken(HttpServletRequest req, HttpServletResponse res){
      // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
      String signature = req.getParameter("signature");
      // 时间戳
      String timestamp = req.getParameter("timestamp");
      // 随机数
      String nonce = req.getParameter("nonce");
      // 随机字符串
      String echostr = req.getParameter("echostr");


      PrintWriter out = null;
      try {
         out = res.getWriter();
         out.print(echostr);
         // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，否则接入失败
//         if (SignUtil.checkSignature(signature, timestamp, nonce)) {
//            out.print(echostr);
//         }
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         out.close();
         out = null;
      }
      System.out.println(req);
   }



   /**
    * 生成加油站的二维码地址 和 参数
    * @param sysDepart
    * @return
    */
   public SysDepart getStationTicket(SysDepart sysDepart) throws IOException, ParseException {
      //请求路径
      StringBuffer url = new StringBuffer();
      url.append("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=");


      String token = getToken();
      url.append(token);
      String  json = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+sysDepart.getOrgCode()+"\"}}}";
      String str = HttpRequest.sendPost(url.toString(),json);

      JSONObject jsonObject = new JSONObject();
      jsonObject = JSONObject.parseObject(str);
      //{"ticket":"gQH47joAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL2taZ2Z3TVRtNzJXV1Brb3ZhYmJJAAIEZ23sUwMEmm
      //	3sUw==","expire_seconds":60,"url":"http://weixin.qq.com/q/kZgfwMTm72WWPkovabbI"}
      String ticketUrl  = jsonObject.getString("url");
      String ticket = jsonObject.getString("ticket");

      //sysDepart.setTicketUrl(ticketUrl);
      //sysDepart.setTicket(ticket);

      System.out.println(" 获取 ticketUrl "+ticketUrl+" ticket ="+ticket);
      //
      String str2 = HttpRequest.sendGet("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket,"");
      System.out.println(" 获取结果 "+str2);
      return sysDepart;

   }

   /**
    * 获取access_token
    * @return
    * @throws ParseException
    */
   public String getToken() throws ParseException {
      SysWxCampus campus = sysWxCampusService.getById(1);
      String access_token = "";
      if(campus!=null){

         long time = (long) (campus.getCreateTime().getTime()+1000*60*60*1.7);
         Date current = new Date();
         long currTime = current.getTime();

         Map<String, Object> params = new HashMap<>();
         String url = null;
         if(currTime>time){
            url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+campus.getAppId()+"&secret="+campus.getAppSecret();
            String str = HttpRequest.sendGet(url,"");
            JSONObject jsonObject = new JSONObject();
            jsonObject = JSONObject.parseObject(str);

            //{"access_token":"ACCESS_TOKEN","expires_in":7200}
            access_token = jsonObject.getString("access_token");

            campus.setCreateTime(new Date());
            campus.setAccessToken(access_token);

            sysWxCampusService.updateById(campus);
         }
      }
      return access_token;
   }





}
